//
//  token.cpp
//  Soo
//
//  Created by leviathan on 15/9/8.
//  Copyright (c) 2015年 leviathan. All rights reserved.
//

#include <iostream>
#include <fstream>
#include "global.h"
#include "token.h"
using namespace std;

char * token::string2char(string str)
{
    return const_cast<char *>(str.c_str());
}
bool token::tokeninit()
{
    cout<<"please enter source file path and name :";
    cin>>infile;
    ifstream search;
    search.open(string2char(infile));
    if(!search)
        cout<<"source file "<<infile<<" not find "<<endl;
    while (!search) {
        cout<<"please input correct file  path and name"<<endl;
        cin>>infile;
        search.open(string2char(infile));
    }
    cout<<"please enter output file path and name:";
    cin>>outfile;
    ofstream newoutfile;
    newoutfile.open(string2char(outfile));
    if(newoutfile)
        cout<<"file "<<outfile<<" is create success "<<endl;
    return true;
}

void token::readline()
{
    int index,length;
    ifstream code;
    code.open(string2char(infile));
    string line;
    while (getline(code, line)) {
        length=int(line.length());
        index=0;
        while (index<length) {
            //num
            if(line[index]>='0'&&line[index]<='9')
            {
                string token="";
                token+=line[index];
                index++;
                while (line[index]>='0'&&line[index]<'9') {
                    token+=line[index];
                    index++;
                }
                codestream.push_back(token);
            }
            //id
            else if((line[index]>='a'&&line[index]<'z')||(line[index]>='A'&&line[index]<='Z'))
            {
                string token="";
                token+=line[index];
                index++;
                while ((line[index]>='a'&&line[index]<'z')||(line[index]>='A'&&line[index]<='Z')||(line[index]>='0'&&line[index]<'9')) {
                    token+=line[index];
                    index++;
                }
                codestream.push_back(token);
            }
            //symbol
            else if(line[index]=='['||line[index]==']'||line[index]=='+'||line[index]=='-'||line[index]=='*'||line[index]=='/'||line[index]==';')
            {
                string token="";
                token+=line[index];
                index++;
                codestream.push_back(token);
            }
            //comments
            else if (line[index]=='#')
            {
                index++;
                while (index<length) {
                    index++;
                }
            }
            //space
            else
                index++;
        }
    }
}
